#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import ConfigParser as configparser
import getopt
from urlparse import parse_qs
from sys import argv, exit

# for Python3.6
# import configparser

config_file_path = 'assets/config.ini'
cf = configparser.ConfigParser()
cf.read(config_file_path)
server_host = cf.get('auth', 'server_host')
server_port = cf.get('auth', 'server_port')
server_base_url = 'http://' + server_host + ':' + server_port
auth_url = server_base_url + '/auth'
authorization_header = "TK-Authorization"


def get_auth_token():
    payload = {
        'username': cf.get('auth', 'username'),
        'password': cf.get('auth', 'password')
    }

    r = requests.post(auth_url, data=payload, allow_redirects=False)
    token = None
    if r.status_code == requests.codes.ok and r.json()['success']:
        token = r.json()['data']['token']
    return token


def get_authed_header():
    return {
        authorization_header: get_auth_token()
    }


def post(url=None, parm=''):
    print("sending request: " + server_base_url + url + "?" + parm)
    print("====================")
    r = requests.post(server_base_url + url, data=parse_qs(parm), headers=get_authed_header())
    return r


def get(url=None, parm="1=1"):
    print("sending request: " + server_base_url + url + "?" + parm)
    print("====================")
    r = requests.get(server_base_url + url + "?" + parm, headers=get_authed_header())
    return r


def test_user_list():
    print (get('/user/list', "page=1&rows=10").content)
    print("=====================")
    print (post('/menu/preview').content)


def usage():
    print("""
参数说明:
    --url: 目标测试的请求的地址
    --parm: 请求参数
    --method: 请求方法，目前支持post或者get(不填写默认get)
    --test: 运行自检测试命令，不支持其他参数

命令参考:
    python tksite_http.py --url "/user/list" --parm "page=1&rows=10"
""")


if __name__ == '__main__':
    if len(argv[1:]) == 0:
        usage()
        exit()

    opts, args = getopt.getopt(argv[1:], "hu:",
                               ["help", "test", "method=", "url=", "parm=", "test="])

    r_method = 'get'
    r_parm_string = '1=1'
    r_url = None

    for name, value in opts:
        if name in ['-u', '--url']:
            r_url = value
        elif name in ['-p', '--parm']:
            r_parm_string = value
        elif name in ['-m', '--method']:
            r_method = value
        elif name in ['-t', '--test']:
            test_user_list()
            exit()
        elif name in ['-h', '--help']:
            usage()
            exit()

    if r_url is None:
        print('url cant be empty!')
        exit()

    if r_method == 'get':
        print (get(r_url, r_parm_string).content)
    elif r_method == 'post':
        print (post(r_url, r_parm_string).content)
    else:
        print('unsupported http method yet!')
        exit()
